package com.example.administrator.zkdemo.activity;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Base64;

import com.example.administrator.zkdemo.application.MainApplication;
import com.example.administrator.zkdemo.db.orm.manager.DataManager;
import com.orhanobut.logger.Logger;
import com.zkteco.android.core.sdk.HubProtocolManager;
import com.zkteco.android.db.orm.tna.AttLog;
import com.zkteco.android.utils.StrUtil;
import com.zkteco.android.utils.ZKFilePath;
import com.zkteco.android.view.dialog.LoadingDialog;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class SplashActivity extends Activity {
    DataManager dataManager;
    LoadingDialog mDialog;

    private void addAttLog(Date paramDate) {
        SimpleDateFormat localSimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.getDefault());
        AttLog localAttLog = new AttLog();
        localAttLog.setUser_PIN("1");
        localAttLog.setVerify_Time(localSimpleDateFormat.format(paramDate));
        localAttLog.setVerify_Type(15);
        localAttLog.setStatus(255);
        try {
            localAttLog.create();
            return;
        } catch (Exception paramDate) {
            paramDate.printStackTrace();
        }
    }

    private void checkPath(File paramFile) {
        if (!paramFile.exists()) {
            paramFile.mkdirs();
            Logger.d("checkPath: ");
        }
    }

    private void initHub() {
        HubProtocolManager localHubProtocolManager = new HubProtocolManager(this);
        localHubProtocolManager.hubServiceInit();
        try {
            Thread.sleep(2000L);
        } catch (InterruptedException localInterruptedException) {
            localInterruptedException.printStackTrace();
        }
        localHubProtocolManager.connectHubServer();
    }

    private void initPath() {
        checkPath(new File(ZKFilePath.APP_PATH));
        checkPath(new File(ZKFilePath.IMAGE_PATH));
        checkPath(new File(ZKFilePath.AD_PICTURE_PATH));
        checkPath(new File(ZKFilePath.AD_VIDEO_PATH));
        checkPath(new File(ZKFilePath.PHOTO_PATH));
        checkPath(new File(ZKFilePath.FACE_PATH));
        checkPath(new File(ZKFilePath.LOGCAT_PATH));
        checkPath(new File("/data/data/com.zkteco.android.core/databases/pushconfig"));
    }

    public String getDeviceSN() {
        Object localObject = new File("system/etc/ZKTeco/serial_number");
        if ((((File) localObject).exists()) && (!((File) localObject).isDirectory()))
            try {
                localObject = new FileInputStream((File) localObject);
                byte[] arrayOfByte = new byte[256];
                StringBuffer localStringBuffer = new StringBuffer();
                while (((FileInputStream) localObject).read(arrayOfByte) != -1)
                    localStringBuffer.append(new String(arrayOfByte));
                ((FileInputStream) localObject).close();
                localObject = new String(Base64.decode(localStringBuffer.toString(), 0));
                return localObject;
            } catch (IOException localIOException) {
                localIOException.printStackTrace();
                return "";
            } catch (FileNotFoundException localFileNotFoundException) {
                localFileNotFoundException.printStackTrace();
                return "";
            }
        Logger.e("system/etc/ZKTeco/serial_number file not exists", new Object[0]);
        return (String) "";
    }

    protected void onCreate(@Nullable Bundle paramBundle) {
        super.onCreate(paramBundle);
        setContentView(2131427367);
        this.mDialog = new LoadingDialog(this);
        ((MainApplication) getApplication()).getSmdtManager().smdtSetStatusBar(this, false);
        new MyTask(this).execute(new Object[0]);
    }

    static class MyTask extends AsyncTask {
        final String SYSTEM_DB_INITED_TAG_FILE = "/data/data/com.zkteco.android.core/isSystemDbInit.dat";
        private WeakReference<SplashActivity> weakAty;

        public MyTask(SplashActivity paramSplashActivity) {
            this.weakAty = new WeakReference(paramSplashActivity);
        }

        private void initConfig() {
            if (!isSystemDbInited()) {
                copyFile("/mnt/sdcard/config/push/options.cfg", "/data/data/com.zkteco.android.core/databases", "/options.cfg");
                setSystemDbInited();
            }
            copyFile("/mnt/sdcard/config/push/Android.infoscreen.tabledesc.xml", "/data/data/com.zkteco.android.core/databases/pushconfig", "/Android.infoscreen.tabledesc.xml");
            copyFile("/mnt/sdcard/config/push/standalonetabledesc.xml", "/data/data/com.zkteco.android.core/databases", "/standalonetabledesc.xml");
            copyFile("/mnt/sdcard/config/push/push.ini", "/data/data/com.zkteco.android.core/databases/pushconfig", "/push.ini");
            copyFile("/mnt/sdcard/config/push/post.txt", "/data/data/com.zkteco.android.core/databases", "/post.txt");
        }

        private void initSytemDb() {
            initConfig();
            SplashActivity localSplashActivity = (SplashActivity) this.weakAty.get();
            if (new File("/data/data/com.zkteco.android.core/databases/options.cfg").exists())
                localSplashActivity.dataManager.systemInitOptionTable();
            Logger.d("#########system-free####");
            localSplashActivity.dataManager.systemInit();
        }

        private boolean isSystemDbInited() {
            return new File("/data/data/com.zkteco.android.core/isSystemDbInit.dat").exists();
        }

        private boolean needUpdate() {
            StringBuilder localStringBuilder = new StringBuilder();
            localStringBuilder.append(Environment.getExternalStorageDirectory().getPath());
            localStringBuilder.append("/ZKTeco/image/photo");
            return new File(localStringBuilder.toString()).exists();
        }

        private void setSystemDbInited() {
            File localFile = new File("/data/data/com.zkteco.android.core/isSystemDbInit.dat");
            try {
                localFile.createNewFile();
                return;
            } catch (IOException localIOException) {
                localIOException.printStackTrace();
            }
        }

        private void upGrade() {
            Object localObject1 = new StringBuilder();
            ((StringBuilder) localObject1).append(Environment.getExternalStorageDirectory().getPath());
            ((StringBuilder) localObject1).append("/ZKTeco/image");
            localObject1 = ((StringBuilder) localObject1).toString();
            Object localObject2 = new StringBuilder();
            ((StringBuilder) localObject2).append(Environment.getExternalStorageDirectory().getPath());
            ((StringBuilder) localObject2).append("/ZKTeco/image/photo");
            localObject2 = ((StringBuilder) localObject2).toString();
            Object localObject3 = new StringBuilder();
            ((StringBuilder) localObject3).append(Environment.getExternalStorageDirectory().getPath());
            ((StringBuilder) localObject3).append("/ZKTeco/SuperFaceP/ad");
            localObject3 = ((StringBuilder) localObject3).toString();
            Object localObject4 = new StringBuilder();
            ((StringBuilder) localObject4).append(Environment.getExternalStorageDirectory().getPath());
            ((StringBuilder) localObject4).append("/ZKTeco/SuperFaceP/ad/picture");
            localObject4 = ((StringBuilder) localObject4).toString();
            Object localObject5 = new StringBuilder();
            ((StringBuilder) localObject5).append(Environment.getExternalStorageDirectory().getPath());
            ((StringBuilder) localObject5).append("/ZKTeco/SuperFaceP/ad/video");
            localObject5 = ((StringBuilder) localObject5).toString();
            Object localObject6 = new StringBuilder();
            ((StringBuilder) localObject6).append(Environment.getExternalStorageDirectory().getPath());
            ((StringBuilder) localObject6).append("/ZKTeco/image/face");
            localObject6 = ((StringBuilder) localObject6).toString();
            copyDir((String) localObject2, ZKFilePath.PHOTO_PATH);
            copyDir((String) localObject4, ZKFilePath.AD_PICTURE_PATH);
            copyDir((String) localObject5, ZKFilePath.AD_VIDEO_PATH);
            copyDir((String) localObject6, ZKFilePath.FACE_PATH);
            StrUtil.deleteFile(new File((String) localObject2));
            StrUtil.deleteFile(new File((String) localObject4));
            StrUtil.deleteFile(new File((String) localObject5));
            StrUtil.deleteFile(new File((String) localObject6));
            StrUtil.deleteFile(new File((String) localObject1));
            StrUtil.deleteFile(new File((String) localObject3));
            ((SplashActivity) this.weakAty.get()).dataManager.executeSql("ZKDB.db", "UPDATE Pers_BioTemplate SET template_no=? where ID is not null", new Object[]{Integer.valueOf(1)});
        }

        protected void copyDir(String paramString1, String paramString2) {
            File[] arrayOfFile = new File(paramString1).listFiles();
            if (arrayOfFile == null)
                return;
            int i = 0;
            while (i < arrayOfFile.length) {
                String str = arrayOfFile[i].getName();
                StringBuilder localStringBuilder = new StringBuilder();
                localStringBuilder.append(paramString1);
                localStringBuilder.append("/");
                localStringBuilder.append(str);
                copyFile(localStringBuilder.toString(), paramString2, str);
                i += 1;
            }
        }

        protected void copyFile(String paramString1, String paramString2, String paramString3) {
            Object localObject = new StringBuilder();
            ((StringBuilder) localObject).append(paramString2);
            ((StringBuilder) localObject).append(paramString3);
            localObject = new File(((StringBuilder) localObject).toString());
            File localFile = new File(paramString1);
            if ((!((File) localObject).exists()) && (localFile.exists()))
                StrUtil.copyToFilesystem(MainApplication.getContext(), paramString1, paramString2, paramString3);
        }

        protected Object doInBackground(Object[] paramArrayOfObject) {
            paramArrayOfObject = (SplashActivity) this.weakAty.get();
            paramArrayOfObject.initPath();
            StrUtil.deleteFile(new File("/mnt/sdcard/config"));
            StrUtil.copyFilesFromAssets(MainApplication.getContext(), "config", "/mnt/sdcard/config/");
            paramArrayOfObject.dataManager = new DataManager();
            paramArrayOfObject.dataManager.init(paramArrayOfObject);
            paramArrayOfObject.dataManager.open(paramArrayOfObject);
            upGrade();
            Logger.d("#########system-copy####");
            initSytemDb();
            try {
                Thread.sleep(2000L);
            } catch (InterruptedException paramArrayOfObject) {
                paramArrayOfObject.printStackTrace();
            }
            return null;
        }

        protected void onPostExecute(Object paramObject) {
            super.onPostExecute(paramObject);
            paramObject = (SplashActivity) this.weakAty.get();
            String str = paramObject.getDeviceSN().replaceAll("\r|\n", "").replaceAll("\r|\n", "").trim();
            if (!TextUtils.isEmpty(str))
                paramObject.dataManager.setStrOption("~SerialNumber", str);
            try {
                Logger.d("#########");
                Thread.sleep(1000L);
            } catch (InterruptedException localInterruptedException) {
                localInterruptedException.printStackTrace();
            }
            paramObject.initHub();
            // 跳转到ZKSignInActivity
            ZKSignInActivity.actionStart(MainApplication.getContext());
            paramObject.finish();
        }

        protected void onPreExecute() {
            super.onPreExecute();
            if (needUpdate()) {
                SplashActivity localSplashActivity = (SplashActivity) this.weakAty.get();
                localSplashActivity.mDialog.setText("正在更新数据...");
                localSplashActivity.mDialog.show();
            }
        }
    }
}
